<template>
  <div class="flex flex-col h-full">
    <vxe-card title="" class="w-full" :border="false">
      <div class="flex items-center">
        <div class="border-arrow" @click="toPrevPage">
          <FontIcon icon="icon-left" />
        </div>
        <div class="text-[#242930] ml-4">
          {{ t("expiry_detail.edit_prepare") }} - {{ verQuery.name }} -
          {{ row.name }}
        </div>
      </div>
    </vxe-card>

    <vxe-card title="" class="w-full mt-4" :border="false" :padding="false">
      <div class="wrap p-[20px] pt-0">
        <div :class="TITLE_CLASS" style="margin-top: 0">
          <div class="flex items-center">
            <div class="w-[2px] h-[14px] bg-[--el-color-primary]" />
            <div class="text-[#242930] text-sm ml-[10px]">
              {{ t("expiry_detail.prepare_info") }}
            </div>
          </div>
        </div>
        <div class="relative">
          <el-descriptions :column="2" border class="desc-item">
            <el-descriptions-item label-align="right">
              <template #label>
                <div class="cell-item">
                  {{ t("expiry_detail.upload_formula") }}：
                </div>
              </template>
              <el-upload
                :show-file-list="false"
                class="upload-empDocs"
                action="/autata/file/upload"
                accept="image/*"
                :before-upload="uploadImgPreview"
                :data="{ foldername: 'expiry' }"
                @success="e => onSuccess(e, 'img')"
              >
                <img
                  v-if="prepareInfo.formulaUrl"
                  :src="handleImgURL(prepareInfo.formulaUrl)"
                  class="h-full"
                  alt="配方图片上传"
                />
                <div v-else class="text-center">
                  <FontIcon icon="icon-upload" />
                  {{ t("expiry_detail.formula_image") }}
                </div>

                <div
                  v-if="prepareInfo.formulaUrl"
                  class="close"
                  @click="remove($event, 'formulaUrl')"
                >
                  <IconifyIconOffline icon="ep:close" />
                </div>
              </el-upload>
            </el-descriptions-item>
            <el-descriptions-item label-align="right">
              <template #label>
                <div class="cell-item">
                  {{ t("expiry_detail.upload_video") }}：
                </div>
              </template>
              <div class="w-[24%] relative">
                <el-upload
                  ref="videoUploadRef"
                  :show-file-list="false"
                  class="upload-empDocs"
                  action="/autata/file/upload"
                  accept="video/*"
                  :data="{ foldername: 'expiry' }"
                  :before-upload="uploadPreview"
                  :on-progress="handleProgress"
                  @success="e => onSuccess(e, 'video')"
                >
                  <video
                    v-if="prepareInfo.makeUrl"
                    :src="handleImgURL(prepareInfo.makeUrl)"
                    class="h-full"
                    controls
                  />
                  <div v-else class="text-center">
                    <FontIcon icon="icon-upload" />
                    {{ t("expiry_detail.make_video") }}
                  </div>

                  <div
                    v-if="prepareInfo.makeUrl"
                    class="close"
                    @click="remove($event, 'makeUrl')"
                  >
                    <IconifyIconOffline icon="ep:close" />
                  </div>
                </el-upload>
                <div
                  v-if="percentage"
                  class="upload-process flex flex-col items-center"
                >
                  <el-progress
                    type="dashboard"
                    class="mt-2"
                    :percentage="percentage"
                    :color="colors"
                  />
                  <el-button
                    type="primary"
                    size="small"
                    class="mt-[-4px]"
                    @click="cancelUpload"
                    >{{ t("expiry_detail.cancel_upload") }}</el-button
                  >
                </div>
              </div>
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <div :class="[TITLE_CLASS, 'mt-0']">
          <div class="flex items-center">
            <div class="w-[2px] h-[14px] bg-[--el-color-primary]" />
            <div class="text-[#242930] text-sm ml-[10px]">
              {{ t("expiry_detail.operation_steps") }}
            </div>
          </div>
        </div>

        <el-tabs
          v-model="prepareStep"
          v-loading="loading"
          type="border-card"
          editable
          :class="['expiry-tab', prepareStepList.length ? '' : 'empty-tab']"
          @edit="handleTabsEdit"
        >
          <template #add-icon>
            <iconify-icon-online icon="ion:add" />
            {{ t("expiry_detail.add_step") }}
          </template>
          <el-tab-pane
            v-for="item in prepareStepList"
            :key="item.stepNum"
            :label="item.title"
            :name="item.stepNum"
          >
            <el-form
              ref="tabRef"
              :model="item"
              :rules="prepareRules"
              label-suffix=" :"
              label-width="120px"
              class="text-[--autata-font-gray-color]"
            >
              <el-form-item :label="t('expiry_detail.step_name')" prop="name">
                <el-input
                  v-model="item.name"
                  :maxlength="30"
                  style="width: 200px"
                  :placeholder="t('expiry_detail.enter_step_name')"
                />
              </el-form-item>
              <el-form-item :label="t('expiry_detail.step_time')" prop="time">
                <el-time-picker
                  v-model="item.time"
                  style="width: 200px"
                  value-format="HH:mm:ss"
                  :default-value="new Date('1974-01-01 00:00:00')"
                  :placeholder="t('expiry_detail.select_time')"
                />
              </el-form-item>
              <el-form-item
                :label="t('expiry_detail.step_description')"
                prop="content"
              >
                <el-input
                  v-model="item.content"
                  type="textarea"
                  :maxlength="200"
                  style="width: 400px"
                  :placeholder="t('expiry_detail.enter_step_description')"
                />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>

      <div
        class="flex items-center justify-end mt-[16px] px-[20px] py-[10px] border-t border-[--autata-border-color]"
      >
        <el-button @click="toPrevPage">{{ t("buttons.cancel") }}</el-button>
        <el-button type="primary" @click="confirm">{{
          t("buttons.confirm")
        }}</el-button>
      </div>
    </vxe-card>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, onMounted, reactive, ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { TITLE_CLASS } from "@/views/expiry/material/materialManage/constants";
import {
  ElMessage,
  FormRules,
  TabPaneName,
  TabsPaneContext
} from "element-plus";
import { ResultProps } from "@/api/user";
import { cloneDeep } from "lodash-unified";
import {
  materialMakeAdd,
  materialMakeGetList,
  materialMakeUpd
} from "@/api/expiry/expiry";
import { useI18n } from "vue-i18n";

const { t } = useI18n();

defineOptions({
  name: "expiryDetail"
});

// region 声明ref变量集合
const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();
let verQuery = ref({
  versionId: "",
  name: ""
});
let row = ref({
  materialId: "",
  materialSource: "",
  name: ""
});

const prepareInfo = ref({
  id: null,
  formulaUrl: "",
  makeUrl: "uploadfile/autata/expiry/3cd19399-f7ba-4071-9bac-11c31c2721b7.mp4",
  stepList: "[]",
  materialId: "",
  materialSource: "",
  versionId: "",
  name: ""
});
const prepareRules = reactive<
  FormRules<{
    name: string;
    time: string;
    content: string;
  }>
>({
  name: [
    {
      required: true,
      message: t("expiry_detail.enter_step_name"),
      trigger: "blur"
    }
  ],
  time: [
    {
      required: true,
      message: t("expiry_detail.select_time"),
      trigger: "blur"
    },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value) {
          const [hours, minutes, seconds] = value.split(":");
          const totalSeconds =
            parseInt(hours) * 3600 + parseInt(minutes) * 60 + parseInt(seconds);
          if (totalSeconds === 0) {
            callback(new Error(t("expiry_detail.step_time_zero")));
          } else {
            callback();
          }
        } else {
          callback(new Error(t("expiry_detail.select_time_prepare")));
        }
      },
      trigger: "blur"
    }
  ],
  content: [
    {
      required: true,
      message: t("expiry_detail.enter_step_description"),
      trigger: "blur"
    }
  ]
});
const prepareStep = ref(1);
const prepareStepList = ref([]);
const loading = ref(false);

const timeList = ref([]);
const percentage = ref(0);

const colors = [
  { color: "#f56c6c", percentage: 20 },
  { color: "#e6a23c", percentage: 40 },
  { color: "#5cb87a", percentage: 60 },
  { color: "#1989fa", percentage: 80 },
  { color: "#6f7ad3", percentage: 100 }
];

const tabRef = ref();
const videoUploadRef = ref();
// endregion

// region 公共方法的集合
function handleImgURL(url: string) {
  const proxyPath = import.meta.env?.VITE_PROXY_PATH ?? "/";
  const isInclude = url.includes("http");
  if (!isInclude) {
    return proxyPath + url;
  }
  return url;
}

function getTimeIntervals(intervalMinutes: number) {
  let timeIntervals = [];
  for (let hour = 0; hour < 24; hour++) {
    for (let minute = 0; minute < 60; minute += intervalMinutes) {
      let hourStr = hour.toString().padStart(2, "0");
      let minuteStr = minute.toString().padStart(2, "0");
      const time = `${hourStr}:${minuteStr}`;
      timeIntervals.push({
        value: time,
        label: time
      });
    }
  }
  return timeIntervals;
}

function addStep(val: number) {
  prepareStepList.value.push({
    title: `步骤${val + 1}`,
    name: "",
    time: "",
    stepNum: val + 1,
    content: ""
  });
  prepareStep.value = val + 1;
}

function secondsToHMS(seconds: number) {
  let hours = Math.floor(seconds / 3600);
  let minutes = Math.floor((seconds % 3600) / 60);
  let remainingSeconds = seconds % 60;

  // 格式化小时、分钟和秒，确保它们始终是两位数
  let formattedHours = String(hours).padStart(2, "0");
  let formattedMinutes = String(minutes).padStart(2, "0");
  let formattedSeconds = String(remainingSeconds).padStart(2, "0");

  return `${formattedHours}:${formattedMinutes}:${formattedSeconds}`;
}

function getPrepareInfo() {
  row.value = JSON.parse(route.query?.row as string);
  if (row.value.materialId) {
    const { versionId } = verQuery.value;
    const param = {
      materialId: row.value.materialId,
      versionId
    };
    materialMakeGetList({
      start_page: 1,
      size: 1,
      filter: param
    }).then(res => {
      if (res.data?.length) {
        prepareInfo.value = res.data[0];
        if (prepareInfo.value.stepList) {
          const stepList = JSON.parse(prepareInfo.value.stepList);
          prepareStepList.value = stepList.map(item => {
            item.time = secondsToHMS(item.time);
            console.log(item);
            return item;
          });
        }
      } else {
        prepareInfo.value = {
          id: null,
          formulaUrl: "",
          makeUrl: "",
          stepList: "[]",
          materialId: "",
          materialSource: "",
          versionId: "",
          name: ""
        };
      }
    });
  }
}

// endregion

// region 组件事件的集合
const toPrevPage = () => {
  router.push({
    name: "expiryMaterialDetail",
    query: {
      ...verQuery.value
    }
  });
};

const remove = (e: MouseEvent, key: string) => {
  e.stopPropagation();
  prepareInfo.value[key] = "";
};

const uploadImgPreview = file => {
  const isLt = file.size / 1024 / 1024 < 10;

  if (!isLt) {
    ElMessage.error(t("expiry_detail.upload_image_size", { size: 10 }));
    return false;
  }
};
const uploadPreview = file => {
  const isLt = file.size / 1024 / 1024 < 300;

  if (!isLt) {
    ElMessage.error(t("expiry_detail.upload_video_size", { size: 300 }));
    return false;
  }
};

const handleProgress = (event, file) => {
  // event 包含了上传进度的信息
  console.log(`文件 ${file.name} 上传进度：${event.percent}%`);
  // 你可以根据 event.percent 来更新 UI，显示上传进度
  percentage.value = Math.floor(event.percent);
};

const cancelUpload = () => {
  videoUploadRef.value.abort();
  percentage.value = 0;
};

const onSuccess = (
  rawFile: ResultProps<{
    path: string;
    relative_path: string;
    size: number;
  }>,
  key: string
) => {
  if (key === "img") {
    prepareInfo.value.formulaUrl = rawFile.data.relative_path;
  } else if (key === "video") {
    prepareInfo.value.makeUrl = rawFile.data.relative_path;
  }
  percentage.value = 0;
};

const handleTabsEdit = (
  targetName: TabPaneName | undefined,
  action: "remove" | "add"
) => {
  if (action === "add") {
    if (prepareStepList.value.length > 6) {
      proxy.$auMessageBox.alert(
        t("expiry_detail.max_steps"),
        t("notice.title")
      );
      return;
    }
    addStep(prepareStepList.value.length);
  } else if (action === "remove") {
    const tabs = cloneDeep(prepareStepList.value);
    let activeName = prepareStep.value;
    if (activeName === targetName) {
      tabs.forEach((tab, index) => {
        if (tab.stepNum === targetName) {
          const nextTab = tabs[index + 1] || tabs[index - 1];
          if (nextTab) {
            activeName = nextTab.stepNum;
          }
        }
      });
    }

    prepareStepList.value = tabs
      .filter(tab => tab.stepNum !== targetName)
      .map((v, i) => {
        return { ...v, title: `步骤${i + 1}` };
      });
    prepareStep.value = activeName;
  }
};

const cancel = () => {};

const confirm = async () => {
  if (
    !prepareInfo.value.formulaUrl &&
    !prepareInfo.value.makeUrl &&
    !prepareStepList.value.length
  ) {
    proxy.$auMessageBox.alert(
      t("expiry_detail.prepare_required"),
      t("notice.title")
    );
    return;
  }
  if (tabRef.value?.length) {
    for (let i = 0; i < tabRef.value?.length; i++) {
      const ele = tabRef.value[i];
      const valid = await ele.validate(valid => valid);
      if (!valid) {
        prepareStep.value = i + 1;
        return;
      }
    }
  }

  let service = materialMakeAdd;
  if (prepareInfo.value?.id) {
    service = materialMakeUpd;
  } else {
    prepareInfo.value.materialId = row.value.materialId;
    prepareInfo.value.materialSource = row.value.materialSource;
    prepareInfo.value.versionId = verQuery.value.versionId;
  }
  prepareInfo.value.name = row.value.name;
  if (prepareStepList.value.length) {
    const stepList = cloneDeep(prepareStepList.value).map((item, i) => {
      item.stepNum = i + 1;
      const [hours, minutes, seconds] = item.time.split(":");
      item.time =
        parseInt(hours) * 3600 + parseInt(minutes) * 60 + parseInt(seconds);
      return item;
    });
    prepareInfo.value.stepList = JSON.stringify(stepList);
  } else {
    prepareInfo.value.stepList = "[]";
  }

  service(prepareInfo.value).then(res => {
    ElMessage({
      message: prepareInfo.value?.id
        ? t("expiry_detail.modify_success_prepare")
        : t("expiry_detail.add_success_prepare"),
      type: "success"
    });
    toPrevPage();
  });
};

// endregion

onMounted(() => {
  const query = route.query?.verQuery;
  verQuery.value = JSON.parse(query as string);
  getPrepareInfo();
  // timeList.value = getTimeIntervals(1);
});
</script>

<style lang="scss" scoped>
.expiry-tab {
  :deep(.el-tabs__new-tab) {
    width: auto;
    margin-right: 10px;
    color: var(--el-color-primary);
    border: none;
  }

  :deep(.el-tabs__header) {
    min-height: 40px;
  }

  :deep(.el-tabs__content) {
    min-height: 200px;
  }
}

.desc-item {
  :deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
    width: 165px;
  }
}

:deep(.clock) {
  width: 24px;
  height: 24px;
  margin-left: 20px;
  cursor: pointer;
  outline: none;
  fill: #9fa6b0;

  &:hover {
    fill: #ea2626;
  }
}

.upload-empDocs {
  position: relative;
  width: 25vw;
  height: 160px;
  border-radius: 2px;

  .close {
    position: absolute;
    top: 0;
    right: 0;
    width: 26px;
    height: 26px;
    font-size: 24px;
    text-align: center;
    background-color: #00000020;

    &:hover {
      color: #3595fd;
      background-color: #00000040;
    }

    svg {
      display: inline-block;
      margin-top: 50%;
      transform: translateY(-45%);
    }
  }

  &::before {
    position: absolute;
    inset: 0;
    pointer-events: none; /* 确保伪元素不会影响鼠标事件 */
    content: "";
    border: 2px dashed var(--autata-border-color);
    transition: border-color 0.3s ease; /* 平滑过渡边框颜色 */
  }

  &:hover::before {
    border-color: var(--el-color-primary);
  }

  :deep(.el-upload) {
    width: 100%;
    height: 100%;
    color: var(--el-color-primary);

    .iconfont {
      display: block;
      margin: 0 auto;
      font-size: 24px;
    }
  }
}

.upload-process {
  position: absolute;
  top: 0;
  left: 0;
  width: 25vw;
  height: 160px;
  background-color: #00000060;

  :deep(.el-progress__text) {
    color: #fff;
  }
}
</style>
